package club.janna.jrpc.config;

import club.janna.jrpc.annotation.JRPCReference;
import club.janna.jrpc.annotation.JRPCService;
import club.janna.jrpc.util.JRPCBootstrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;

/**
 * @author Panbo.Guo
 */
@Slf4j
public class JRPCPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Autowired
    private JRPCProperties jrpcProperties;

    private JRPCBootstrap bootstrap;

    @PostConstruct
    public void initBootstrap() {
        bootstrap = JRPCBootstrap.builder()
                .registry(jrpcProperties.getRegistry())
                .protocol(jrpcProperties.getProtocol())
                .host(jrpcProperties.getHost())
                .port(jrpcProperties.getPort())
                .serialization(jrpcProperties.getSerialization())
                .transport(jrpcProperties.getTransport())
                .build();
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        JRPCService annotation = bean.getClass().getAnnotation(JRPCService.class);
        if(annotation != null) {
            // 发布服务
            bootstrap.publish(bean);
        }

        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            JRPCReference jrpcReference = field.getAnnotation(JRPCReference.class);
            if(jrpcReference != null) {
                field.setAccessible(true);
                try {
                    // 引用服务
                    field.set(bean, bootstrap.reference(field.getType(), jrpcReference.loadBalancer()));
                } catch (IllegalAccessException e) {
                    log.error("引用远程服务出错");
                }
            }
        }
        return true;
    }
}
